package com.db.yupao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.db.yupao.common.ErrorCode;
import com.db.yupao.exception.BusinessException;
import com.db.yupao.model.enums.TeamStatusEnum;
import com.db.yupao.model.pojo.Team;
import com.db.yupao.model.pojo.User;
import com.db.yupao.model.pojo.UserTeam;
import com.db.yupao.service.TeamService;
import com.db.yupao.mapper.TeamMapper;
import com.db.yupao.service.UserTeamService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

/**
 * 45
 *
 * @author 23245
 * @description 针对表【team(队伍)】的数据库操作Service实现
 * @createDate 2025-08-22 09:49:08
 */
@Service
@Slf4j
public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team>
        implements TeamService {

    @Resource
    private UserTeamService userTeamService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public long addTeam(Team team, User loginUser) {
        if (team == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        if(loginUser == null){
            throw new BusinessException(ErrorCode.NO_LOGIN);
        }
        // 设置默认值
        int maxNum = Optional.ofNullable(team.getMaxNum()).orElse(0);
        log.info("maxNum: " + maxNum);

        if (maxNum < 1 || maxNum > 20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "最大人数不符合要求");
        }

        String name = team.getName();
        if ( StringUtils.isAnyBlank(name) ||  name.isBlank() || name.length() >20 ){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR, "队伍名称不符合要求");
        }
        // 队伍描述
        String description = team.getDescription();
        if( StringUtils.isNotBlank(description) && description.length() > 512 ){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍描述过长");
        }
        // 判断状态码
        Integer status = team.getStatus();
        TeamStatusEnum enumByValue = TeamStatusEnum.getEnumByValue(status);
        if(enumByValue == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍状态错误");

        }
        String password = team.getPassword();
        if(TeamStatusEnum.SECRET.equals(enumByValue) && StringUtils.isNotBlank(password)){
            if ( password.length()>32 ){
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码设置不正确");
            }
        }
        // 判断超时时间
        Date expireTime = team.getExpireTime();
        if ( ! new Date().before(expireTime)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "超时时间必须大于当前时间");
        }

        // 判断用户创建了几个队伍
        // todo  有bug  后续应该需要加锁
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",loginUser.getId());
        long count = this.count(queryWrapper);
        if (count > 5){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "最多创建5个队伍");
        }

        // 插入队伍信息到队伍表
        team.setId(null);
        team.setUserId(loginUser.getId());
        // 应该先保存这个队伍信息
        boolean saveFlag = this.save(team);
        // 应该在保存之后获取ID
        Long teamId = team.getId();
            if (!saveFlag || teamId == null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创建队伍失败");
        }

        // 插入用户  到队伍关系表
        UserTeam userTeam = new UserTeam();
        userTeam.setTeamId(teamId);
        userTeam.setUserId(loginUser.getId());
        userTeam.setJoinTime(new Date());

        saveFlag = userTeamService.save(userTeam);
        if (!saveFlag){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创建队伍失败");
        }


        return teamId;
    }
}




